﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

using BlogPlat.Model;
using BlogPlat.Model.Abstract;

namespace BlogPlat.Controllers
{
    public class PostController : Controller
    {
        private IPostRepository _repository;

        public PostController(IPostRepository repository)
        {
            _repository = repository;
        }
       
        /// <summary>
        /// Index action that returns newest blog posts sorted by date
        /// </summary>                
        public ActionResult Index()
        {           
            return View(_repository.ListNewestPublishedPosts());           
        }
        
        public ActionResult Index(int? year, int? month, int? day)
        {
            return View(_repository.ListBlogEntriesArchive(year, month, day));
        }

        [RequireRequestValue("friendlyUrl")]       
        public ActionResult FriendlyUrl(string friendlyUrl)
        {
            if (!string.IsNullOrEmpty(friendlyUrl.Trim()))
            {
                Post post = _repository.GetByFriendlyUrl(friendlyUrl);
                if (post != null)
                {
                    // Increment view count
                    _repository.IncrementViewCount(post.ID);
                    _repository.Save();

                    return View(post);
                }
                else
                {
                    // Implement custom 404                    
                }
            }            

            return RedirectToAction("Index");
        }
    }

    public class RequireRequestValueAttribute : ActionMethodSelectorAttribute
    {
        public RequireRequestValueAttribute(string valueName)
        {
            ValueName = valueName;
        }
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            return (controllerContext.HttpContext.Request[ValueName] != null);
        }
        public string ValueName { get; private set; }
    }
}
